import os
import shutil
from PIL import Image
import hashlib

'''
遍历路径A和路径B，找出同名的文件。
对于txt文件，比较内容和修改时间，如果相同则删除B中的文件。
对于图片文件，比较大小和分辨率，如果相同则删除B中的文件。
'''

def get_file_hash(file_path):
    """ 获取文件的MD5哈希值，便于比较内容是否相同 """
    hash_md5 = hashlib.md5()
    with open(file_path, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


def get_image_info(image_path):
    """ 获取图片的分辨率和大小 """
    with Image.open(image_path) as img:
        resolution = img.size  # (width, height)
        file_size = os.path.getsize(image_path)  # 文件大小（字节）
    return resolution, file_size


def collect_files(path):
    """ 收集指定路径下所有txt和图片文件的相关信息 """
    file_info = {}
    for root, _, files in os.walk(path):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith(".txt"):
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                file_info[file_path] = {'type': 'txt', 'content': content, 'modified_time': os.path.getmtime(file_path)}
            elif file.endswith((".png", ".jpg", ".jpeg")):
                resolution, size = get_image_info(file_path)
                file_info[file_path] = {'type': 'image', 'resolution': resolution, 'size': size}
    return file_info


def compare_and_delete(path_a, path_b):
    """ 比较A路径和B路径中的同名文件，删除符合条件的B路径文件 """
    a_files = collect_files(path_a)
    b_files = collect_files(path_b)

    for b_file, b_info in b_files.items():
        # 获取文件名
        b_filename = os.path.basename(b_file)

        # 查找路径A中的同名文件
        a_file = os.path.join(path_a, b_filename)

        if a_file in a_files:
            a_info = a_files[a_file]
            if b_info['type'] == 'txt' and a_info['type'] == 'txt':
                # 比较txt文件内容和修改时间
                if b_info['content'] == a_info['content']: # and b_info['modified_time'] == a_info['modified_time']:
                    print(f"Deleting file: {b_file} (txt)")
                    os.remove(b_file)
            elif b_info['type'] == 'image' and a_info['type'] == 'image':
                # 比较图片文件的分辨率和大小
                if b_info['resolution'] == a_info['resolution'] and b_info['size'] == a_info['size']:
                    print(f"Deleting file: {b_file} (image)")
                    os.remove(b_file)
                # elif b_info['resolution'] == a_info['resolution'] and b_info['size'] < a_info['size']:
                #     print(f"Not same, smaller, Deleting file: {b_file} (image)")
                #     os.remove(b_file)


# 示例调用

path_a = "/home/champrin/Desktop/record_data/网盘/兑换框数据集/2023-自家框 高曝光"
path_b = "/home/champrin/Desktop/record_data/网盘/兑换框数据集/2024-兑换框"
compare_and_delete(path_a, path_b)

